import React from 'react';
import { Menu } from 'antd';
import Link from 'umi/link'
import getIcon from '../MyIcon';

import styles from './styles.less'
import { connect } from 'dva';
import { Dispatch } from 'typings/redux';

export interface IMenu {
  name: string,
  id: number,
  url?: string,
  children?: Array<IMenu>
}

const { SubMenu } = Menu;

export interface IProps {
  dispatch?: Dispatch;
  menu?: Array<IMenu>
}

@connect()
class BaseMenu extends React.PureComponent<IProps> {

  getNavMenuItems = menusData => {
    if (!Array.isArray(menusData)) return [];

    return menusData.map((v, index) => this.getSubMenuOrItem(v, index))
  }

  getKey(e, v) {
    const [mainKey, subKey] = e.key.split('-')
    window.sessionStorage.setItem('subKey', subKey);
    window.sessionStorage.setItem('mainKey', mainKey);
    window.sessionStorage.setItem('menuId', v.id);
    sessionStorage.removeItem('pageKeySub');

    const { dispatch } = this.props;
    dispatch({
      type: 'menu/queryButton',
      payload: v.id
    })
  }

  componentDidMount() {
    const menuId = window.sessionStorage.getItem('menuId');
    const { dispatch } = this.props;
    menuId && dispatch({
      type: 'menu/queryButton',
      payload: menuId
    })
  }

  getSubMenuOrItem = (item, ind) => {
    if (item.children && item.children.some(v => v.name)) {
      const { name } = item;
      return (
        <SubMenu
          className={styles.menu}
          title={
            item.remark ? (
              <span>
                {getIcon(item.remark)}
                <span>{name}</span>
              </span>
            ) : (
                name
              )
          }
          key={ind}
        >
          {
            item.children.map((v, index) => 
            <Menu.Item 
              key={`${ind}-${index}`}
              onClick={(e) => this.getKey(e, v)}
            >
              <Link to={v.url} style={{ fontSize: '15px' }}>{v.name}</Link>
            </Menu.Item>
          )
          }
        </SubMenu>
      );
    }

    return null;
  }


  render() {
    const menu = this.props.menu;

    const subKey = window.sessionStorage.getItem('subKey') || '0';
    const mainKey = window.sessionStorage.getItem('mainKey') || '0';

    return (
      <Menu
        mode="inline"
        theme="dark"
        defaultSelectedKeys={[`${mainKey}-${subKey}`]}
        style={{ height: '100%', borderRight: 0, background: '#2C4254' }}
      >
        {this.getNavMenuItems(menu)}
      </Menu>
    )
  }
}

export default BaseMenu;
